#include<stdio.h>
#include "../include/vfs.h"
#include "../include/create_vfs.h"
#include<string.h>
#include<stdlib.h>


#define per_fd 0.01


int create_vfs(char vfs_name[], long vfs_size)
{

	FILE *fp;

	long num_fdesc;
	long i;
        long num_blocks;
	 
        Block *block;
 	
	if(strlen(vfs_name)>30)
		return 7;

	num_blocks = vfs_size;

	vfs_size = vfs_size*1000;

	if(!valid_name(vfs_name))
		return 4;
	
	strcpy(filesystem_name,vfs_name);

	if(vfs_size<1000 || vfs_size>1024000)
		return 5;

	fp = fopen(vfs_name,"r+b");

	if(fp!=NULL){
		
		header = malloc(sizeof(Header));

		fread(header,sizeof(Header),1,fp);
		if(strcmp(header->vfslabel,vfs_name)==0)
		{
			fclose(fp);
			return 1;
		}
	}
	
      
//**********************************************************************************************************************************
	if(vfs_size==1000)
	{
		num_fdesc=900;
		//num_blocks = 1;
	}
	else if(vfs_size<500000)
	{	
		num_fdesc=900;
		//num_blocks = (long)((vfs_size)/sizeof(Block));
     
	}

	else
	{
		num_fdesc=900;
		//num_blocks = (long)(vfs_size-sizeof(Header)-(per_fd*vfs_size))/(sizeof(Block));

	}
//****************************************************************************************************************************************
   
	header=malloc(sizeof(Header));
    	strcpy(header->vfslabel,vfs_name);
	
	header->max_FD=num_fdesc;
	
	header->used_FD=0;
	header->num_blocks=num_blocks;

	for(i=0;i<header->num_blocks;i++)
	{
		header->freelist[i].block=i+1;
		header->freelist[i].isfree=1;
	
	}
	
	for(i=0;i<header->max_FD;i++)
	{

		header->fd_list[i].block_no=0;
	}
		
	
	fp = fopen(vfs_name,"w+b");

	if(fp==NULL)
		return 2;

	fwrite(header,sizeof(Header),1,fp);
	
//******************************************************************************************************************************************	


	block=malloc(sizeof(Block));

	block->num=1;
	fwrite(block, sizeof(Block), 1,fp);

	for(i=1; i<(num_blocks); i++)
	{	
		block->num=i+1;
		fwrite(block, sizeof(Block), 1,fp);
	}
   
	

	initialize_vfs();
   
 	//fclose(fp);

       return 0;
}

